<template>
  <el-row :gutter="20" id="userAppPage">
    <!-- 查询表单 -->
    <el-col :span="4" :offset="0" id="userAppPageForm">
      <el-form :model="appRequestForm" label-width="90px">
        <div id="userAppPageFormTitleWrapper">
          <div>查询条件</div>
        </div>
        <el-form-item label="应用 id" prop="id">
          <el-input v-model="appRequestForm.id" clearable placeholder="无限制" />
        </el-form-item>
        <el-form-item label="排除应用 id" prop="notId">
          <el-input v-model="appRequestForm.notId" clearable placeholder="无限制" />
        </el-form-item>
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="appRequestForm.appName" clearable placeholder="无限制" />
        </el-form-item>
        <el-form-item label="应用描述" prop="appDesc">
          <el-input v-model="appRequestForm.appDesc" clearable placeholder="无限制" />
        </el-form-item>
        <el-form-item label="搜索词" prop="searchText">
          <el-input v-model="appRequestForm.searchText" clearable placeholder="无限制" />
        </el-form-item>
        <el-form-item label="应用类型" prop="appType">
          <el-select v-model="appRequestForm.appType" placeholder="无限制">
            <el-option label="无限制" value=""></el-option>
            <el-option v-for="appTypeName in Object.keys(AppTypeEnum).filter(key => Number.isNaN(Number(key)))"
              :label="AppTypeEnumMap[appTypeName as keyof typeof AppTypeEnumMap]"
              :value="AppTypeEnum[appTypeName as keyof typeof AppTypeEnum]">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评分策略" prop="scoringStrategy">
          <el-select v-model="appRequestForm.scoringStrategy" placeholder="无限制">
            <el-option label="无限制" value=""></el-option>
            <el-option
              v-for="scoringStrategyName in Object.keys(ScoringStrategyEnum).filter(key => Number.isNaN(Number(key)))"
              :label="ScoringStrategyEnumMap[scoringStrategyName as keyof typeof ScoringStrategyEnumMap]"
              :value="ScoringStrategyEnum[scoringStrategyName as keyof typeof ScoringStrategyEnum]">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="reviewStatus">
          <el-select v-model="appRequestForm.reviewStatus" placeholder="无限制">
            <el-option label="无限制" value=""></el-option>
            <el-option
              v-for="reviewStatusName in Object.keys(ReviewStatusEnum).filter(key => Number.isNaN(Number(key)))"
              :label="ReviewStatusEnumMap[reviewStatusName as keyof typeof ReviewStatusEnumMap]"
              :value="ReviewStatusEnum[reviewStatusName as keyof typeof ReviewStatusEnum]">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核信息" prop="reviewMessage">
          <el-input v-model="appRequestForm.reviewMessage" clearable placeholder="无限制" />
        </el-form-item>
        <el-form-item label="审核人 id" prop="reviewerId">
          <el-input v-model="appRequestForm.reviewerId" clearable placeholder="无限制" />
        </el-form-item>
        <el-form-item label="排序字段" prop="sortField">
          <el-select v-model="appRequestForm.sortField" placeholder="无限制">
            <el-option
              v-for="validSortField in Object.keys(ValidSortFieldEnum).filter(key => Number.isNaN(Number(key)))"
              :label="ValidSortFieldEnumMap[validSortField as keyof typeof ValidSortFieldEnumMap]"
              :value="ValidSortFieldEnum[validSortField as keyof typeof ValidSortFieldEnum]">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序顺序" prop="sortOrder">
          <el-select v-model="appRequestForm.sortOrder" placeholder="无限制">
            <el-option label="升序" :value="SqlSortOrderEnum.ASC"></el-option>
            <el-option label="降序" :value="SqlSortOrderEnum.DESC"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <el-button type="primary" size="default" @click="doSearch" :loading="isLoading">查询</el-button>
    </el-col>

    <!-- 查询结果表格 -->
    <el-col :span="20" :offset="0" id="userAppPageTable">
      <!-- 分页 -->
      <el-pagination @size-change="onSizeChange" @current-change="doSearch" v-model:currentPage="appRequestForm.current"
        :page-sizes="[5, 10, 15, 20]" :page-size="appRequestForm.pageSize" layout="total, sizes, prev, pager, next"
        :total="totalNum" background :pager-count="9" :disabled="paginationDisabled">
      </el-pagination>

      <!-- 数据 -->
      <el-table stripe :data="tableData" height="78vh" v-loading="isLoading">
        <el-table-column width="180" show-overflow-tooltip fixed="left" prop="id" label="应用 id" />
        <el-table-column width="180" show-overflow-tooltip prop="appName" label="应用名称" />
        <el-table-column width="180" show-overflow-tooltip prop="appDesc" label="应用描述" />
        <el-table-column width="80" show-overflow-tooltip prop="appIcon" label="应用图片">
          <template #default="scope">
            <template v-if="scope.row.appIcon">
              <img :src="scope.row.appIcon" style="max-width: 100px; height: 32px;" />
            </template>
          </template>
        </el-table-column>
        <el-table-column width="100" show-overflow-tooltip prop="appType" label="应用类型">
          <template #default="scope">
            {{ AppTypeEnumMap[AppTypeEnum[scope.row.appType] as keyof typeof AppTypeEnumMap] }}
          </template>
        </el-table-column>
        <el-table-column width="100" show-overflow-tooltip prop="scoringStrategy" label="评分类型">
          <template #default="scope">
            {{ ScoringStrategyEnumMap[ScoringStrategyEnum[scope.row.scoringStrategy] as keyof typeof
            ScoringStrategyEnumMap] }}
          </template>
        </el-table-column>
        <el-table-column width="80" show-overflow-tooltip prop="reviewStatus" label="审核状态">
          <template #default="scope">
            {{ ReviewStatusEnumMap[ReviewStatusEnum[scope.row.reviewStatus] as keyof typeof ReviewStatusEnumMap] }}
          </template>
        </el-table-column>
        <el-table-column width="180" show-overflow-tooltip prop="reviewMessage" label="审核消息" />
        <el-table-column width="180" show-overflow-tooltip prop="reviewerId" label="审核人 id" />
        <el-table-column width="180" show-overflow-tooltip prop="reviewTime" label="审核时间" />
        <el-table-column width="180" show-overflow-tooltip prop="createTime" label="创建时间" />
        <el-table-column width="180" show-overflow-tooltip prop="updateTime" label="信息更新时间" />
        <el-table-column width="420" fixed="right" label="操作">
          <template #default="scope">
            <div class="buttonWrapper">
              <el-button size="small" type="info" plain :icon="Edit" @click="doGoToAppPage(scope.$index, scope.row)">
                编辑应用
              </el-button>
              <el-button size="small" type="info" plain :icon="Edit" @click="doGoToQuestionPage(scope.$index, scope.row)">
                编辑题目
              </el-button>
              <el-button size="small" type="info" plain :icon="Edit" @click="doGoToScoringResultPage(scope.$index, scope.row)"
              :class="scope.row.scoringStrategy === ScoringStrategyEnum.AI ? 'invisible' : ''">
                编辑评分策略
              </el-button>
              <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(scope.$index, scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { AppTypeEnum, AppTypeEnumMap, ResponseCodeEnum, ReviewStatusEnum, ReviewStatusEnumMap, ScoringStrategyEnum, ScoringStrategyEnumMap, SqlSortOrderEnum, ValidSortFieldEnum, ValidSortFieldEnumMap } from '@/enums';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref } from 'vue';
import { Delete, Edit } from '@element-plus/icons-vue';
import { deleteAppUsingDelete, listAppByPageUsingPost, listMyAppVoByPageUsingPost } from '@/api/appController';
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useLoginUserStore } from '@/stores/userStore';

const router = useRouter();
const loginUserStore = useLoginUserStore();

// 表单查询请求数据
const appRequestForm = ref<API.AppQueryRequest>({
  id: undefined,
  notId: undefined,
  userId: loginUserStore.loginUser.id,
  appName: '',
  appDesc: '',
  searchText: '',
  appType: undefined,
  scoringStrategy: undefined,
  reviewStatus: undefined,
  reviewMessage: '',
  reviewerId: undefined,
  current: 1,
  pageSize: 10,
  sortField: ValidSortFieldEnum.createTime,
  sortOrder: SqlSortOrderEnum.DESC,
});

// 查询结果
const tableData = ref<API.App[]>([]);

// 查询总数
const totalNum = ref(0);

// 查询按钮是否正在加载中
const isLoading = ref(false);

// 分页插件是否可用
const paginationDisabled = ref(true);

/**
 * 当一页的数据量改变时触发
 * @param pageSize 当前一页容量
 */
const onSizeChange = (pageSize: number) => {
  appRequestForm.value.pageSize = pageSize;
  appRequestForm.value.current = 1;
  doSearch();
}

/**
 * 执行查询
 */
const doSearch = async () => {
  // 点过一次查询按钮后, 才启用分页插件
  paginationDisabled.value = false;

  isLoading.value = true;
  const result = await listAppByPageUsingPost(appRequestForm.value);
  
  if (result.data.code === ResponseCodeEnum.SUCCESS) {
    // 更新表单数据与总数
    tableData.value = result.data.data?.records || [];
    totalNum.value = Number(result.data.data?.total) || 0;
  } else {
    ElMessage.error("获取数据失败: " + result.data.message);
  }

  isLoading.value = false;
}

/**
 * 删除应用
 * @param index 所在行号
 * @param row 所在行数据
 */
const handleDelete = (index: number, row: API.App) => {
  ElMessageBox.confirm(
    '此操作将删除该应用, 是否继续 ?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const result = await deleteAppUsingDelete({
      id: row.id
    })

    if (result.data.code === ResponseCodeEnum.SUCCESS) {
      ElMessage.success(`成功删除 id = ${row.id} 的应用`);
      doSearch();
    } else {
      ElMessage.error("删除失败: " + result.data.message);
    }
  }).catch(() => { })
}

/**
 * 跳转到修改应用页面
 */
const doGoToAppPage = (index: number, row: API.App) => {
  router.push({
    name: '修改应用',
    params: {
      id: row.id
    }
  })
}

/**
 * 跳转到修改题目页面
 */
const doGoToQuestionPage = (index: number, row: API.App) => {
  router.push({
    name: '编辑题目',
    params: {
      appId: row.id
    }
  })
}

/**
 * 跳转到编辑评分规则页面
 */
const doGoToScoringResultPage = (index: number, row: API.App) => {
  router.push({
    name: '编辑评分策略',
    params: {
      appId: row.id
    }
  })
}

// 上来先查一次
onMounted(() => {
  doSearch();
})
</script>

<style scoped lang="less">
#userAppPage {
  height: 100%;
  width: 100%;
}

#userAppPageForm {
  border-right: 1px solid rgb(220, 223, 230);

  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: left;
  align-items: center;

  .el-button {
    width: 90%;
  }
}

#userAppPageFormTitleWrapper {
  height: 6vh;
  display: flex;
  justify-content: center;
  align-items: center;

  div {
    font-size: 1.5rem;
  }
}

#userAppPageTable {
  overflow: hidden;

  .el-pagination {
    margin: 10px 0;
  }
}

#questionListWrapper {
  height: 100px;
  overflow: hidden;
  position: absolute;
}

.invisible {
  visibility: hidden;
}
</style>